<?php

namespace app\index\controller;

use addons\wechat\model\WechatCaptcha;
use app\common\controller\Frontend;
use app\common\library\Ems;
use app\common\library\MyWeChat;
use app\common\library\Sms;
use app\common\model\Attachment;
use think\Config;
use think\Cookie;
use think\Exception;
use think\Hook;
use think\Session;
use think\Validate;

use fast\Random;
use PDO;
use think\Response;
use think\cache\driver\Redis;
use think\Db;

/**
 * 任务
 */
class Task extends Frontend
{
    protected $layout = '';
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 首页
     */
    public function upgrade()
    {
        $this->assign("title", "任务列表");
        //任务百分比
        $userId = $this->auth->id;
        $user = Db::name('user')->where(['id' => $userId])->find();
        if ($user['is_upgraded_expert_level'] != 0) {
            $total = Db::name("expert_upgrade_order")->where(["user_id" => $userId, 'upgrade_type' => $user['upgradeing_expert_level']])->count();
            $complete = Db::name("expert_upgrade_order")->where(["user_id" => $userId, 'status' => 2, 'upgrade_type' => $user['upgradeing_expert_level']])->count();
        } else {
            $total = Db::name("expert_upgrade_order")->where(["user_id" => $userId, 'upgrade_type' => $user['expert_level']])->count();
            $complete = Db::name("expert_upgrade_order")->where(["user_id" => $userId, 'status' => 2, 'upgrade_type' => $user['expert_level']])->count();
        }

        $percent = ($total == 0 ? 0 : $complete / $total);
        $this->assign('total', intval($total));
        $this->assign('complete', intval($complete));;
        $this->assign('percent', $percent * 100);
        if ($user['upgradeing_expert_level'] != 0) {

            $list = Db::name("expert_upgrade_order")
                ->field("o.id,u.nickname,u.avatar,u.mobile,o.status,o.order_type,o.upgrade_type,o.expiretime,o.expiretime")
                ->alias('o')
                ->join('user u', 'u.id=o.up_user_id')
                ->where(["o.user_id" => $userId, 'o.upgrade_type' => $user['upgradeing_expert_level']])
                ->order("order_type ASC,o.id ASC")
                ->select();

        } else {
            $list = Db::name("expert_upgrade_order")
                ->field("o.id,u.nickname,u.avatar,u.mobile,o.status,o.order_type,o.upgrade_type,o.expiretime,o.expiretime")
                ->alias('o')
                ->join('user u', 'u.id=o.up_user_id')
                ->where(["o.user_id" => $userId, 'o.upgrade_type' => $user['expert_level']])
                ->order("order_type ASC,o.id ASC")
                ->select();
        }
        foreach ($list as &$value) {
            $value['avatar'] = ($value['avatar'] == '' ? '' : cdnurl($value['avatar'], true));
            $value['expiretime'] = $value['expiretime'] - time();
            $value['expiretime'] = ($value['expiretime'] > 0 ? $value['expiretime'] : 0);
        }
        $this->assign('list', $list);
        return $this->view->fetch();
    }

    /**
     * 去补单
     */
    public function placeOrder()
    {
        $user = Db::name("user")->where(["id" => $this->auth->id])->find();
        if ($user['qr_code'] == '') {
            $this->success('请先设置橱窗二维码！', url("index/user/setqrcode", ['bak' => '1']));
        }
        $parent_user_id = $user['parent_user_id'];
        $up_user = Db::name("user")->where(["id" => $parent_user_id])->find();

        //星号手机号
        $maskPhoneNumber = $up_user["mobile"] ? hidtel($up_user["mobile"]) : "";
        $show_name = $up_user["nickname"];
        if (!$show_name) {
            $show_name = $maskPhoneNumber;
        }

        $rule_list = Db::name('expert_level_rule')->order('price asc')->select();
        $this->assign('rule_list', $rule_list);
        $this->assign('up_user', $up_user);
        $this->assign("maskPhoneNumber", $maskPhoneNumber);
        $this->assign("show_name", $show_name);

        $this->assign("title", "升级任务");
        return $this->view->fetch('place_order');
    }

    public function details()
    {
        $user = Db::name("user")->where(["id" => $this->auth->id])->find();
        if ($user['qr_code'] == '') {
            $this->success('请先设置橱窗二维码！', url("index/user/setqrcode", ['bak' => '1']));
        }

        $upgradeOrderId = $this->request->param('id');
        $num = $this->request->param('num');
        $order = Db::name('expert_upgrade_order')->where(['id' => $upgradeOrderId])->find();
        $up_user = Db::name("user")->where(["id" => $order['up_user_id']])->find();

        //星号手机号
        $maskPhoneNumber = $up_user["mobile"] ? hidtel($up_user["mobile"]) : "";
        $show_name = $up_user["nickname"];
        if (!$show_name) {
            $show_name = $maskPhoneNumber;
        }
        $order['order_sn'] = explode(',', $order['order_sn']);
        $this->assign('order', $order);
        $this->assign('num', $num + 1);
        $this->assign('up_user', $up_user);
        $this->assign("maskPhoneNumber", $maskPhoneNumber);
        $this->assign("show_name", $show_name);
        return $this->view->fetch('details');
    }

    /*
     * 任务结果提交
     */
    public function subOrder()
    {
        $user_id = $this->auth->id;
        if (!$user_id) $this->error('登录状态异常');

        $user_info = Db::name('user')->field('score,h5_score,coupon_count,expert_level')->where(['id' => $user_id])->find();
        if(empty($user_info)) apiReturn(2,'用户信息不存在');

        $orderNum = $this->request->param('orderNum/a');
        if (count($orderNum) <= 0 || $orderNum[0] == '') apiReturn(2, '至少输入一个订单总编号');

        $wechat_order_list = Db::name('wechat_orders')->field('order_sn,order_price,is_used')->whereIn('order_sn', $orderNum)->select();
        if (count($orderNum) != count($wechat_order_list)) apiReturn(2, '请仔细核对，存在错误的订单编号');

        $all_money = 0;
        foreach ($wechat_order_list as $v) {
            if ($v['is_used'] == 1) apiReturn(2, '订单编号' . $v['order_sn'] . '已被使用');

            // order_price 单位是分
            $all_money += $v['order_price'];
        }

        $all_money = $all_money / 100;

        $orderNum = implode(',', $orderNum);

        $rule_list = Db::name('expert_level_rule')->order('price desc')->select();
        $expert_level = 0;
        $score = 0;
        $coupon_count = 0;
        if ($rule_list) {
            foreach ($rule_list as $v) {
                if ($all_money >= $v['price']) {
                    $expert_level = $v['expert_level'];
                    $score = $v['score'];
                    $coupon_count = $v['coupon_count'];
                    break;
                }
            }
        }

        if($expert_level == 0) apiReturn(2,'订单总金额未达到升级条件');
//        if($expert_level <= $user_info['expert_level']) apiReturn(2,'订单总金额未达到下一级升级条件');

        Db::startTrans();
        try {
            $time = time();

            $data = [
                'order_sn' => $orderNum,
                'user_id' => $user_id,
                'upgrade_type' => $expert_level,
                'all_money' => $all_money,
                'addtime' => $time
            ];
            $id = Db::name('expert_upgrade_order')->insertGetId($data);

            $wechat_data = [
                'user_id' => $user_id,
                'task_id' => $id,
                'is_used' => 1,
                'status' => 1,
                'updatetime' => $time
            ];
            Db::name('wechat_orders')->whereIn('order_sn', $orderNum)->update($wechat_data);

            if($expert_level > $user_info['expert_level']){
                // 级别升级
                $user_data = [
                    'expert_level' => $expert_level,
                    'h5_score' => $user_info['h5_score'] + $score,
                    'coupon_count' => $user_info['coupon_count'] + $coupon_count,
                    'updatetime' => $time
                ];
                Db::name('user')->where(['id' => $user_id])->update($user_data);
            }

            if($score > 0){
                // 生成积分记录
                $score_log = [
                    'user_id' => $user_id,
                    'score' => $score,
                    'before' => $user_info['score'],
                    'after' => $user_info['score'] + $score,
                    'type' => 3,
                    'remark' => '升级赠送',
                    'create_time' => $time,
                    'link_id' => $id,
                    'link_table' => 'fa_expert_upgrade_order',
                    'from' => 2
                ];
                Db::name('mini_user_score_log')->insert($score_log);
            }

            if($coupon_count > 0){
                // 生成抵扣券记录
                $coupon_log = [
                    'user_id' => $user_id,
                    'coupon_count' => $coupon_count,
                    'before' => $user_info['coupon_count'],
                    'after' => $user_info['coupon_count'] + $coupon_count,
                    'type' => 7,
                    'remark' => '升级赠送',
                    'create_time' => $time,
                    'link_id' => $id,
                    'link_table' => 'fa_expert_upgrade_order',
                    'from' => 2
                ];
                Db::name('mini_user_coupon_log')->insert($coupon_log);
            }

            Db::commit();
            apiReturn(1, '提交成功');
        } catch (Exception $e) {
            Db::rollback();
            apiReturn(2, '提交失败');
        }

    }

    /**
     * 去补单
     */
    public function repurchase()
    {

        $level = 0;
        $userId = $this->auth->id; // 分红级别：1三星达人，2一星董事，3二星董事，4三星董事，5区经理人
        $user = Db::name('user')->where(['id' => $userId])->find();
        if (!in_array($level, [1, 2, 3])) {
            $this->error('等级未达到复购条件，请联系平台管理者');
        }

        //读取配置
        $buyConnfig = Db::name('user_weighting_config')->where(['level' => $level])->find();

        //读取当前
        $nowSituation = Db::name("expert_upgrade_order")->where(['level' => $level, 'upgrade_type' => 4, 'order_type' => 2, 'status' => ['<>', 2]])->find();
        if (empty($nowSituation)) {
            $data = [];
            $data['level'] = $level;
            $data['user_id'] = $userId;
            $data['upgrade_type'] = 4;
            $data['order_type'] = 2;
            $data['up_user_id'] = $user['parent_user_id'];
            $data['status'] = 0;
            $data['addtime'] = time();
            $upgradeOrderId = Db::name('expert_upgrade_order')->insertGetId($data);
        } else {
            $upgradeOrderId = $nowSituation['id'];
        }
        $num = Db::name("expert_upgrade_order")->where(["user_id" => $userId, 'upgrade_type' => $user['upgradeing_expert_level']])->count();
        $order = Db::name('expert_upgrade_order')->where(['id' => $upgradeOrderId])->find();
        $up_user = Db::name("user")->where(["id" => $order['up_user_id']])->find();
        $this->assign('order', $order);
        $this->assign('num', $num + 1);
        $this->assign('up_user', $up_user);
        return $this->view->fetch('repurchase');
    }
}
